<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="referrer" content="no-referrer">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>网络收藏夹|首页</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="layui/css/layui.css">
    <style>
        * {
            user-select: none;
        }

        /* 解决没有src属性时出现的边框 */
        img[src=""], img:not([src]){
            opacity:0;
        }

        /* 解决弹出框中select显示难看 */
        .to-fix-select .layui-layer-content {
            overflow: visible !important;
        }

        #userImg {
            font-size: 18px;
            font-weight: bold;
            margin-right: 5px;
            vertical-align: middle;
        }

        .search-div {
            z-index: 999;
            position: absolute;
            top: 16px;
            left: 150px;
            width: 160px;
            height: 30px;
        }

        .search-div input {
            height: 100%;
            font-size: 12px;
            border: none;
            background-color: #393d49;
            color: #b2b2b2;
            padding-right: 26px;
        }

        .search-div .search-close {
            position: absolute;
            top: 4px;
            right: 4px;
            font-size: 20px;
            color: #666;
            display: none;
            cursor: pointer;
        }

        legend {
            cursor: pointer;
        }

        .favorites {
            display: flex;
            flex-wrap: wrap;
            overflow: hidden;
            padding: 10px;
        }

        .favorites li {
            display: flex;
            align-items: center;
            flex-direction: column;
            position: relative;
            padding: 10px 20px;
            cursor: pointer;
            user-select: none;
            border-radius: 4px;
        }

        .favorites li .favorites-bg {
            width: 80px;
            height: 80px;
            line-height: 80px;
            text-align: center;
            border-radius: 50%;
        }

        .favorites li .favorites-bg img {
            width: 50%;
            height: 50%;
            border: 0;
        }

        .favorites li.active {
            background-color: #f2f2f2;
        }

        .favorites li:hover {
            background-color: #f2f2f2;
        }

        .favorites li:hover .favorites-bg {
            background-color: #e5e7e8;
        }

        .favorites li p {
            width: 80px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 10px;
            text-align: center;
        }

        .favorites li .action-icon {
            position: absolute;
            top: 4px;
            right: 0;
            font-size: 20px;
            font-weight: bold;
            color: #666;
            display: none;
            width: 26px;
            height: 26px;
            line-height: 26px;
            text-align: center;
        }

        .favorites li:hover .action-icon {
            display: block;
        }

        /** 开源信息 **/
        .open-source {
            font-size: 12px;
            text-align: center;
        }

        .style-select{
            position: absolute;
            top: 12px;
            right: 140px;
        }

        .style-select .layui-form-switch{
            border:none;
            background-color: #393d49;
        }

        /** 书签模式 **/
        .bookmark .favorites li{
            flex-direction: row !important;
        }

        .bookmark .favorites li .favorites-bg{
            width: 16px !important;
            height: 16px !important;
            line-height: 16px !important;
            text-align: center !important;
            border-radius: 0 !important;
        }

        .bookmark .favorites li .favorites-bg img{
            width: 100% !important;
            height: 100% !important;
            border: 0 !important;
            vertical-align: baseline !important;
        }

        .bookmark .favorites li:hover .favorites-bg{
            background-color: transparent !important;
        }

        .bookmark .favorites li p{
            width: 300px !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
            white-space: nowrap !important;
            margin-top: 0 !important;
            text-align: left !important;
            margin-left: 10px !important;
            line-height: 30px !important;
            padding-right: 4px !important;
        }

        .bookmark .favorites li .action-icon{
            top: 12px !important;
        }

        /* 目录 */
        .catalog {
            box-shadow: none !important;
            border: 1px solid #d2d2d2;
        }

        .catalog ul {
            padding: 10px;
            min-height: 260px;
            min-width: 110px;
        }

        .catalog li {
            line-height: 26px;
            margin-left: 20px;
            overflow: visible;
            list-style-type: disc;
        }

        .catalog li a.layui-this {
            color: #01AAED;
        }

        .notFoundDiv {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .notFoundDiv img {
            width: 100px;
            height: 100px;
            display: block;
            margin: 0 auto;
        }

        .notFoundDiv span{
            display: block;
            text-align: center;
            font-size: 24px;
            color: #c2c2c2;
            margin-top: 20px;
        }

        /* 过渡动画 */
        .lGDtb {
          width: 100px;
          height: 30px;
          text-align: center;
          font-size: 10px;
        }

        .ljZkoB {
          background-color: rgb(255, 87, 34);
          height: 100%;
          width: 6px;
          display: inline-block;
          margin-left: 5px;
          animation: 1.2s ease-in-out -1.2s infinite normal none running cTRFYZ;
        }

        .gPySoS {
          background-color: rgb(255, 87, 34);
          height: 100%;
          width: 6px;
          display: inline-block;
          margin-left: 5px;
          animation: 1.2s ease-in-out -1.1s infinite normal none running cTRFYZ;
        }

        .dVkzjP {
          background-color: rgb(255, 87, 34);
          height: 100%;
          width: 6px;
          display: inline-block;
          margin-left: 5px;
          animation: 1.2s ease-in-out -1s infinite normal none running cTRFYZ;
        }

        .UdOCq {
          background-color: rgb(255, 87, 34);
          height: 100%;
          width: 6px;
          display: inline-block;
          margin-left: 5px;
          animation: 1.2s ease-in-out -0.9s infinite normal none running cTRFYZ;
        }

        .bnWJxh {
          background-color: rgb(255, 87, 34);
          height: 100%;
          width: 6px;
          display: inline-block;
          margin-left: 5px;
          animation: 1.2s ease-in-out -0.8s infinite normal none running cTRFYZ;
        }

        @keyframes cTRFYZ {

          0%,
          40%,
          100% {
            transform: scaleY(0.4);
          }

          20% {
            transform: scaleY(1);
          }
        }

        .search-items {
            position: absolute;
            top: 30px;
            left: 0;
            width: 100%;
            background: #393d49;
            color: #b2b2b2;
            border-radius: 0 0 4px 4px;
            display: none;
        }

        .search-items li {
            padding-left: 10px;
            padding-right: 26px;
            cursor: pointer;
            line-height: 26px;
            font-size: 12px;
            position: relative;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            word-break: break-all;
        }

        .search-items li:hover {
            background: #5fb878;
            color: #fff;
        }

        .search-items li:last-child {
            margin-bottom: 6px;
        }

        .search-items li .history-close {
            color: #fff;
            font-size: 12px;
            position: absolute;
            top: 0;
            right: 8px;
            display: none;
            font-weight: bold;
        }

        .search-items li:hover .history-close {
            display: block;
        }

         #slideBtn {
            display: inline-block;
            margin-right: 10px;
            width: 40px;
            height: 40px;
            line-height: 40px;
            margin-bottom: 1px;
            text-align: center;
            cursor: pointer;
            font-size: 20px;
            background-color: #393D49;
            color: #fff;
            border-radius: 2px;
            opacity: .95;
        }

        #slideBtn:hover {
            opacity: .85
        }
    </style>
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo" style="width: 150px;cursor: pointer;" onclick="window.location.reload();">
            <img src="images/logo.svg" style="margin-right: 6px;width: 24px;vertical-align: text-top;">网络收藏夹
        </div>
        <div class="search-div">
            <input type="text" id="search_name" name="search_name" placeholder="搜索/输入快捷指令" autocomplete="off"
                   class="layui-input">
            <i id="search_close" class="layui-icon layui-icon-close-fill search-close"></i>
            <ul class="search-items"></ul>
        </div>
        <div class="layui-form style-select" lay-filter="styleSelect">
            <div class="layui-input-inline">
                <input type="checkbox" name="viewStyle" lay-skin="switch" lay-text="书签模式|常规模式" lay-filter="viewStyle">
            </div>
        </div>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <a href="javascript:;">
                    <i class="layui-icon layui-icon-user" id="userImg"></i>
                    <span id="username">默认</span>
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="javascript:;" id="changePwd">修改密码</a></dd>
                    <dd><a href="javascript:;" id="changeEmail">修改邮箱</a></dd>
                    <dd><a href="javascript:;" id="importOrExportBtn">导入/备份</a></dd>
                    <dd><a href="javascript:;" id="logout">安全退出</a></dd>
                </dl>
            </li>
        </ul>
    </div>

    <div class="layui-body" id="layuiBody" style="padding: 15px;left: 0;">
        <!-- 内容主体区域 -->
        <div class="layui-btn-container" style="position: fixed;left: 15px;bottom: 44px;z-index: 99999;">
            <span class="layui-icon layui-icon-right" id="slideBtn"></span>
            <button type="button" class="layui-btn layui-btn-sm" id="addCategoryBtn">添加分类</button>
            <button type="button" class="layui-btn layui-btn-sm" id="addFavoritesBtn">添加收藏</button>
        </div>
        <div id="starDiv"></div>
        <div id="main"></div>
        <div id="searchDiv"></div>
        <div class="lGDtb" style="display: none;position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);">
            <div class="ljZkoB"></div>
            <div class="gPySoS"></div>
            <div class="dVkzjP"></div>
            <div class="UdOCq"></div>
            <div class="bnWJxh"></div>
        </div>
    </div>
    <div class="layui-footer" style="left: 0;">
        <p class="open-source">© 2020 在线网络收藏夹 | <a href="https://gitee.com/wangxiaoyuan_2019/web-favorites.git" target="_blank">网站源码</a> | QQ群：<a href="https://jq.qq.com/?_wv=1027&k=uMr09FnI" target="_blank">972265056</a></p>
    </div>
</div>
<!-- 找不到结果 -->
<div id="notFoundDiv" class="notFoundDiv">
    <img src="images/no_data.svg" alt="">
    <span>找不到结果</span>
</div>
<!-- 导入/备份 -->
<div class="layui-tab layui-tab-brief" id="importOrExport" style="display: none;">
    <ul class="layui-tab-title">
        <li class="layui-this">导入</li>
        <li>备份</li>
    </ul>
    <div class="layui-tab-content" style="text-align: center;">
        <div class="layui-tab-item layui-show">
            <button style="margin-top: 30px;" type="button" class="layui-btn" id="import">导入收藏夹</button>
            <div style="margin: 20px 0;color: #999;line-height: 32px;">请将 "export.xml" 文件上传至服务器</div>
        </div>
        <div class="layui-tab-item">
            <button style="margin-top: 30px;" type="button" class="layui-btn" id="export">备份收藏夹</button>
            <div class="layui-form" style="margin: 20px 0;line-height: 32px;">
                <span>备份数据：</span>
                <input type="checkbox" id="favorites" name="favorites" title="收藏" lay-skin="primary" checked>
                <input type="checkbox" id="moment" name="moment" title="瞬间" lay-skin="primary" checked>
                <input type="checkbox" id="task" name="task" title="日程" lay-skin="primary" checked>
                <input type="checkbox" id="search" name="search" title="搜索" lay-skin="primary" checked>
            </div>
        </div>
    </div>
</div>
<!-- 添加收藏表单 -->
<form class="layui-form" action="" id="add-favorites" lay-filter="add-favorites" style="display: none;padding: 10px">
    <div class="layui-form-item">
        <label class="layui-form-label">地址</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="url" id="url_input" required lay-verify="required|url" placeholder="请输入地址" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="name" id="name_input" required lay-verify="required" placeholder="请输入名称" autocomplete="off"
                   class="layui-input">
        </div>
        <i id="url_loading" class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop" style="color: #009688;font-size: 22px;font-weight: bold;margin-top: 6px;display: none;"></i>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">分类</label>
        <div class="layui-input-inline" style="width: 210px;">
            <select name="categoryId" lay-verify="required">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addFavorites">立即提交</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelAddFavorites">取消</button>
        </div>
    </div>
</form>
<!-- 编辑收藏表单 -->
<form class="layui-form" action="" id="update-favorites" lay-filter="update-favorites"
      style="display: none;padding: 10px">
    <input type="hidden" name="id" id="favoritesId">
    <div class="layui-form-item">
        <label class="layui-form-label">地址</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="url" required lay-verify="required|url" placeholder="请输入地址" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="name" required lay-verify="required" placeholder="请输入名称" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">分类</label>
        <div class="layui-input-inline" style="width: 210px;">
            <select name="categoryId" lay-verify="required">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">排序</label>
        <div class="layui-input-inline" style="width: 120px;">
            <input type="text" name="sort" lay-verify="sortNum" placeholder="请输入数值"
                   autocomplete="off"
                   class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">数值越大越靠前</div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">标记</label>
        <div class="layui-input-inline" style="width: 50px;">
            <input type="checkbox" name="star" lay-skin="switch" value="1" lay-filter="starSwitch">
        </div>
        <div class="layui-form-mid layui-word-aux">标记为常用网址</div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">快捷指令</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="shortcut" lay-verify="shortcut" placeholder="例如：打开...或Open..." autocomplete="off"
                   class="layui-input">
            <span style="color: #ff5722;font-size: 12px;padding: 5px 0;display: block;">温馨提示：配合语音输入效果更佳哦</span>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="updateFavorites">立即提交</button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteFavorites">删除</button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-warm" id="settingPwd">管理密码</button>
        </div>
    </div>
</form>
<!-- 管理密码表单 -->
<form class="layui-form" action="" id="setting-pwd" lay-filter="setting-pwd"
      style="display: none;padding: 10px">
    <input type="hidden" name="id" id="pwdId">
    <input type="hidden" name="favoritesId">
    <div class="layui-form-item">
        <label class="layui-form-label">账号</label>
        <div class="layui-input-inline" style="width: 160px;">
            <input type="text" name="account" id="account" required lay-verify="required" placeholder="请输入账号" autocomplete="off"
                   class="layui-input">
        </div>
        <div class="layui-inline">
            <button type="button" id="accountCopy" class="layui-btn layui-btn-warm layui-btn-xs" style="margin-top:8px" data-clipboard-target="#account">复制</button>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline" style="width: 160px;">
            <input type="text" name="password" id="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off"
                   class="layui-input">
        </div>
        <div class="layui-inline">
            <button type="button" id="passwordCopy" class="layui-btn layui-btn-warm layui-btn-xs" style="margin-top:8px" data-clipboard-target="#password">复制</button>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="savePwd">立即提交</button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="unsetPwd">清除密码</button>
        </div>
    </div>
</form>
<!-- 修改密码表单 -->
<form class="layui-form" action="" id="passwordForm" lay-filter="passwordForm" style="display: none;padding: 10px">
    <div class="layui-form-item">
        <label class="layui-form-label">旧密码</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="password" name="oldPassword" required lay-verify="required" placeholder="请输入旧密码"
                   autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">新密码</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="password" name="newPassword" id="newPassword" required lay-verify="required" placeholder="请输入新密码"
                   autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">确认密码</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="password" name="confirmPassword" required lay-verify="required|confirmPassword" placeholder="再次确认新密码"
                   autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="updatePassword">立即提交</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelPwd">取消</button>
        </div>
    </div>
</form>
<!-- 修改邮箱表单 -->
<form class="layui-form" action="" id="emailForm" lay-filter="emailForm" style="display: none;padding: 10px">
    <div class="layui-form-item">
        <label class="layui-form-label">新邮箱</label>
        <div class="layui-input-inline" style="width: 210px;">
            <input type="text" name="newEmail" id="newEmail" required lay-verify="required|email|exitEmail" placeholder="请输入邮箱"
                   autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">验证码</label>
        <div class="layui-input-inline" style="width:132px;">
            <input type="text" name="code" required lay-verify="required" placeholder="请输入验证码"
                   autocomplete="off" class="layui-input">
        </div>
        <input type="button" class="layui-btn layui-btn-sm layui-btn-danger" style="margin-top:4px;width: 68px;" onclick="sendEmailCode(this)" value="点击获取">
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="updateEmail">立即提交</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelEmail">取消</button>
        </div>
    </div>
</form>
<!-- 编辑分类表单 -->
<form class="layui-form" action="" id="update-category" lay-filter="update-category"
      style="display: none;padding: 10px">
    <input type="hidden" name="id">
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline" style="width: 228px;">
            <input type="text" name="name" id="categoryName" required lay-verify="required|category" placeholder="请输入名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">排序</label>
        <div class="layui-input-inline" style="width: 120px;">
            <input type="text" name="sort" id="categorySort" lay-verify="sortNum" placeholder="请输入数值"
                   autocomplete="off"
                   class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">数值越大越靠前</div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">模式</label>
        <div class="layui-input-inline" style="width: 50px;">
            <input type="checkbox" name="bookmark" lay-skin="switch" value="1" lay-filter="bookmarkSwitch">
        </div>
        <div class="layui-form-mid layui-word-aux">强制切换至书签模式</div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="updateCategory">立即提交</button>
            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" id="deleteCategory">删除分类</button>
            <button type="button" class="layui-btn layui-btn-warm layui-btn-sm" id="clean">清空收藏</button>
        </div>
    </div>
</form>
<!-- 目录 -->
<ul id="catalogList" style="display:none;"></ul>
<script src="layui/jquery-3.1.1.min.js"></script>
<script src="layui/layui.js"></script>
<script src="layui/clipboard.min.js"></script>
<script>
    //JavaScript代码区域
    layui.use(['element', 'layer', 'form', 'upload','flow','util'], function () {
        var element = layui.element;
        var layer = layui.layer;
        var form = layui.form;
        var upload = layui.upload;
        var flow = layui.flow;
        var util = layui.util;

        var limit = 40;// 显示个数限制

        var indexMap = new Map();// 弹出层索引容器

        // 点击空白关闭
        $(document).on("click", function(e) {
            var _conss = $('.search-div');//点击的容器范围
            if (!_conss.is(e.target) && _conss.has(e.target).length === 0) {
                $(".search-items").hide();
                $("#search_close").hide();
            }
        });

        // jQuery全局拦截器
        $(document).ajaxSuccess(function(event,xhr,options){
            var result = xhr.responseJSON;
            if(result != undefined && result.code == "1001"){
                window.location.href= "login.html";
            }
        });

        // 根据数组的下标，删除该下标的元素
        Array.prototype.remove = function(val) {
            var index = this.indexOf(val);
            if (index > -1) {
                this.splice(index, 1);
            }
        };

        // 图片懒加载
        flow.lazyimg({elem: 'img.lazy', scrollElem: '#layuiBody'});

        // 固定块
        util.fixbar({
            top: true
            ,bar1: '&#xe68d;'
            ,bar2: '&#xe615;'
            ,bar3: '&#xe637;'
            ,scrollElem: '#layuiBody'
            ,bgcolor: '#393D49'
            ,css: {right: 30, bottom: 50}
            ,click: function(type){
                if(type === 'bar1'){
                    window.location.href = "moment.html";
                }else if(type === 'bar2'){
                    window.location.href = "search.html";
                }else if(type === 'bar3'){
                    window.location.href = "calendar.html";
                }
            }
        });

        //执行实例
        var uploadInst = upload.render({
            elem: '#import' //绑定元素
            , accept: 'file'
            , acceptMime: 'file/xml'
            , exts: 'xml'
            , url: 'favorites/import' //上传接口
            , before: function(obj){
                layer.close(indexMap.get('#importOrExport')); //关闭弹层
                layer.load(); //上传loading
            }
            , done: function (result) {
                layer.closeAll('loading'); //关闭loading
                if (result.code == 0) {
                    window.location.reload();//刷新
                } else {
                    layer.msg('导入失败', {icon: 5});
                }
            }
            , error: function () {
                layer.closeAll('loading'); //关闭loading
                layer.msg('导入失败', {icon: 5});
            }
        });

        // 清除密码
        $("#unsetPwd").click(function(){
            var passwordId = $("#pwdId").val();
            if(passwordId == ""){
                layer.msg('未设置密码');
                return false;
            }
            layer.confirm('确认清除吗?', function(index){
                layer.close(index);

                layer.load();
                $.ajax({
                    type: "DELETE",
                    url: "password/" + passwordId,
                    dataType: "json",
                    success: function (result) {
                        layer.closeAll('loading');
                        if (result.code == 0) {
                            layer.msg('操作成功', {icon: 6});
                            // 重置表单
                            form.val("setting-pwd", {
                                "id": ""
                                , "account": ""
                                , "password": ""
                            });
                        } else {
                           layer.msg('操作失败', {icon: 5});
                        }
                    }
                });
            });
        });

        $("#url_input").on('input',function(){
            var url = $(this).val();
            if(url.startsWith("https://") || url.startsWith("http://")){
                $("#name_input").val("").addClass("layui-disabled").attr("disabled",true);
                $("#url_loading").show();
                // 请求后台解析url
                $.ajax({
                    type: "GET",
                    url: "favorites/url",
                    data: {"url": url},
                    dataType: "json",
                    success: function (result) {
                        $("#name_input").removeClass("layui-disabled").removeAttr("disabled",true);
                        $("#url_loading").hide();

                        if (result.code == 0) {
                            $("#name_input").val(result.data);
                        }
                    },
                    error: function(){
                        $("#name_input").removeClass("layui-disabled").removeAttr("disabled",true);
                        $("#url_loading").hide();
                    }
                });
            }
        });

        $("#settingPwd").click(function () {
            layer.open({
                type: 1,
                title: "管理登录此网站的密码",
                area: '360px',
                content: $('#setting-pwd')
            });
            // 表单赋值
            $.ajax({
                type: "GET",
                url: "password/fid/" + $("#favoritesId").val(),
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        let data = result.data;
                        //给表单赋值
                        form.val("setting-pwd", {
                            "id": data.id
                            , "favoritesId": data.favoritesId
                            , "account": data.account
                            , "password": data.password
                        });
                    } else {
                        form.val("setting-pwd", {
                            "id": ""
                            , "favoritesId": $("#favoritesId").val()
                            , "account": ""
                            , "password": ""
                        });
                    }
                }
            });
        });

        $("#export").click(function () {
            var favorites = $("#favorites").is(":checked")?"1":"0";
            var moment = $("#moment").is(":checked")?"1":"0";
            var task = $("#task").is(":checked")?"1":"0";
            var search = $("#search").is(":checked")?"1":"0";
            layer.close(indexMap.get('#importOrExport'));
            window.location.href = "favorites/export?f=" + favorites + "&m=" + moment + "&t=" + task + "&s=" + search;
        });

        $("#cancelPwd").click(function () {
            layer.close(indexMap.get('#changePwd'));
        });

        $("#cancelEmail").click(function () {
            layer.close(indexMap.get('#changeEmail'));
        });

        $("#cancelAddFavorites").click(function () {
            layer.close(indexMap.get('#add-favorites'));
        });

        // 搜索项绑定点击事件
        $(document).on('click', '.search-items li', function() {
            var text = $(this).text();
            $("#search_name").val(text).focus();
            $(this).parent().hide();
            searchFavorites(text);
        });

        $(document).on('click', '.search-items li .history-close', function(event) {
            event.stopPropagation();

            $(this).parent().remove();
            if($(".search-items").children().length === 0) $(".search-items").hide();

            var text = $(this).parent().text();
            var input_history = JSON.parse(localStorage.getItem("input_history"));
            if(input_history.indexOf(text) >= 0) {
                input_history.remove(text);
                localStorage.setItem("input_history", JSON.stringify(input_history));
            }
        });

        $("#importOrExportBtn").click(function () {
            var index = layer.open({
                type: 1,
                area: '400px',
                title: false,
                content: $('#importOrExport')
            });
            indexMap.set('#importOrExport',index);
        });

        // 添加收藏
        $("#addFavoritesBtn").click(function () {
            var index = layer.open({
                type: 1,
                title: "添加收藏",
                skin: 'to-fix-select',
                area: '400px',
                content: $('#add-favorites')
            });
            indexMap.set('#add-favorites',index);
            // 表单赋值
            form.val("add-favorites", {
                "name": ""
                , "url": ""
            });
        });

        // 关闭搜索
        $("#search_close").click(function () {
            $("#starDiv").show();
            $("#main").show();
            $("#searchDiv").empty();
            $(this).hide();
            $("#search_name").val("").blur();
            $("#notFoundDiv").hide();
            $(".search-items").hide();
        });

        // 搜索指令
        window.searchShortcut = function(name){
            layer.load();
            $.ajax({
                type: "GET",
                url: "favorites/shortcut?key=" + name,
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    $("#search_name").val("");
                    $("#search_close").hide();
                    if (result.code == 0) {
                        $(".favorites-li[data-id=" + result.data.id + "]").click();
                    }else{
                        layer.tips('未找到指令', '#search_name', {tips: 1});
                    }
                }
            });
        };

        // 搜索文本
        window.searchFavorites = function(name){
            $("#main").hide();
            $("#starDiv").hide();
            layer.load();
            $.ajax({
                type: "GET",
                url: "favorites/search",
                data: {"name": name},
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    $("#searchDiv").empty();
                    if (result.code == 0 && result.data.length > 0) {
                        var html = '';
                        html += '<ul class="favorites">';
                        $.each(result.data, function (i, f) {
                            html += '<li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" onclick="openUrl(this)">';
                            html += '   <div class="favorites-bg">';
                            html += '       <img class="lazy" src="images/book.svg" lay-src="' + f.icon + '"/>';
                            html += '   </div>';
                            html += '   <p title="' + f.name + '">' + f.name + '</p>';
                            html += '   <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                            html += '</li>';
                        });
                        html += '</ul>';
                        $("#searchDiv").append(html);
                        imgRender();
                        $("#notFoundDiv").hide();
                        // 存入历史记录
                        var input_history = JSON.parse(localStorage.getItem("input_history"));
                        if (input_history == null || input_history.length >= 5) input_history = [];
                        if (input_history.indexOf(name) < 0) input_history.push(name);
                        localStorage.setItem("input_history", JSON.stringify(input_history));
                    }else{
                        $("#notFoundDiv").show();
                    }
                },
                error: function(){
                    layer.closeAll('loading');
                    layer.msg('服务器异常', {icon: 2});
                }
            });
        };

        // 搜索
        $("#search_name").on("keydown", function (event) {
            // 1.按上下键进入选择模式，并控制，返回键退出选择模式
            // 2.在选择模式时，按下回车跳转超链接，输入值，退出选择模式
            // 3.不在选择模式时，输入框有值，按下回车查询，输入框没有值，按下回车退出查询模式
            if (event.key === "Enter") {
                $(".search-items").hide();
                var activeLi = $(".favorites-li.active:visible")[0];
                if(typeof activeLi !== "undefined"){
                    $(activeLi).click();
                }else{
                    var name = $(this).val().trim();
                    if (name == "") { //退出搜索模式
                        $("#search_close").click();
                    } else if(name.startsWith("打开")||name.startsWith("Open")) { //搜索快捷指令
                        searchShortcut(name);
                    } else {// 搜索文本
                        searchFavorites(name);
                    }
                }
            } else if (event.key === "ArrowDown") {
                $(".search-items").hide();
                var activeLi = $(".favorites-li.active:visible")[0];
                var list = $(".favorites-li:visible");
                if(typeof activeLi === "undefined"){
                    list.eq(0).addClass("active");
                }else{
                    var nextActiveLi;
                    var last;
                    list.each(function(index,item){
                        if($(item).hasClass("active")){
                            var nextIndex = index + 1;
                            nextActiveLi = list[nextIndex];
                            if(nextIndex + 1 === list.length){
                                last = true
                            }
                            return false;
                        }
                    });
                    if(typeof nextActiveLi !== "undefined"){
                        $(activeLi).removeClass("active");
                        $(nextActiveLi).addClass("active");
                        // 滚动
                        if(last){
                            $("#layuiBody").animate({scrollTop: $("#layuiBody")[0].scrollHeight}, 50);
                        }else{
                            elasticScroll(nextActiveLi.offsetTop);
                        }
                    }
                }
            } else if (event.key === "ArrowUp") {
                $(".search-items").hide();
                var activeLi = $(".favorites-li.active:visible")[0];
                var list = $(".favorites-li:visible");
                if(typeof activeLi === "undefined"){
                    list.eq(0).addClass("active");
                }else{
                    var nextActiveLi;
                    var first;
                    list.each(function(index,item){
                        if($(item).hasClass("active")){
                            var nextIndex = index - 1;
                            nextActiveLi = list[nextIndex];
                            if(nextIndex === 0){
                                first = true;
                            }
                            return false;
                        }
                    });
                    if(typeof nextActiveLi !== "undefined"){
                        $(activeLi).removeClass("active");
                        $(nextActiveLi).addClass("active");
                        // 滚动
                        if(first){
                            $("#layuiBody").animate({scrollTop: 0}, 50);
                        }else{
                            elasticScroll(nextActiveLi.offsetTop);
                        }
                    }
                }
            } else if (event.key === "Backspace") {
                // 退出选择模式
                $(".favorites-li.active").removeClass("active");
            }
        }).on("input", function () {
            //退出选择模式
            $(".favorites-li.active").removeClass("active");
        }).on("focus", function () {
           $("#search_close").show();
            var html = '';
            var input_history = JSON.parse(localStorage.getItem("input_history"));
            $.each(input_history, function(index, item) {
                html = '<li>' + item + '<i class="layui-icon layui-icon-close history-close"></i></li>' + html;
            });
            if (html !== "") $(".search-items").empty().append(html).show();
        });
        // 添加收藏
        window.addFavorites = function (categoryId) {
            $("#addFavoritesBtn").click();
            form.val("add-favorites", {
                "categoryId": categoryId
            });
        }
        // 发送验证码
        window.sendEmailCode = function (obj) {
            var email = $("#newEmail").val();
            var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if(email.match(reg)){
                obj.setAttribute("disabled", true);
                obj.value="重试(60)";
                // 倒计时
                var countdown = 59;
                var interval = setInterval(function() {
                    if (countdown == 0) {
                        obj.removeAttribute("disabled");
                        obj.value="点击获取";
                        countdown = 59;
                        clearInterval(interval);
                    } else {
                        obj.setAttribute("disabled", true);
                        obj.value="重试(" + countdown + ")";
                        countdown--;
                    }
                }, 1000);
                // 请求后台
                $.ajax({
                    type: "GET",
                    url: "user/email/code",
                    data: {"email": email}
                });
            }else{
                $("#newEmail").focus().addClass("layui-form-danger");
                 layer.msg('邮箱格式不正确', {icon: 5, anim: 6});
            }
        };

        // 弹性滚动
        window.elasticScroll = function(height){
            var visibleHeight = $("#layuiBody").height();
            var shouldScroll = Math.floor(height/ visibleHeight) * visibleHeight;
            var scrollTop = $("#layuiBody").scrollTop();
            if(Math.abs(scrollTop - shouldScroll) >= visibleHeight){
                $("#layuiBody").animate({scrollTop: shouldScroll}, 50);
            }
        }

        // 打开新窗口
        window.openUrl = function (obj) {
            var url = $(obj).attr("data-url");
            if(url.startsWith("https://") || url.startsWith("http://")){
                $.ajax({
                    type: "GET",
                    url: "favorites/visit/" + $(obj).attr("data-id")
                });
                window.open(url,'_blank');
            }else{
                layer.msg('此链接无效', {icon: 7});
            }
        };

        // 编辑分类
        window.editCategory = function (obj) {
            var index = layer.open({
                type: 1,
                title: "修改分类",
                area: '400px',
                content: $('#update-category')
            });
            indexMap.set('#update-category',index);
            // 表单赋值
            $.ajax({
                type: "GET",
                url: "category/" + $(obj).parent().attr("data-id"),
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        let data = result.data;
                        //给表单赋值
                        form.val("update-category", {
                            "id": data.id
                            , "name": data.name
                            , "sort": data.sort
                            , "bookmark": data.bookmark
                        });
                        //禁用系统分类
                        if (data.isSystem == 1) {
                            $("#categoryName").attr("disabled", true);
                            $("#categorySort").attr("disabled", true);
                        } else {
                            $("#categoryName").removeAttr("disabled");
                            $("#categorySort").removeAttr("disabled");
                        }
                    }
                }
            });
        };

        // 新增分类
        $("#addCategoryBtn").click(function () {
            layer.prompt({title: "添加分类", placeholder:"输入分类名称", maxlength: 10}, function (value, index, elem) {
                // 验证
                var bool = true;
                $.ajax({
                    type: "GET",
                    url: 'category/check/' + value,
                    async: false, // 使用同步的方法
                    dataType: 'json',
                    success: function (result) {
                        if (result.code == 0) {
                            layer.tips('分类已存在', elem, {tips: 3});
                            bool = false;
                        }
                    }
                });
                if(bool){
                    layer.close(index);
                    layer.load();
                    $.ajax({
                        type: "POST",
                        url: "category",
                        data: JSON.stringify({"name": value}),
                        contentType: 'application/json;charset=utf-8',
                        dataType: "json",
                        success: function (result) {
                            layer.closeAll('loading');
                            if (result.code == 0) {
                                window.location.reload();
                            } else {
                                layer.msg("添加失败", {icon: 5});
                            }
                        }
                    });
                }
            });
        });

        // 修改密码
        $("#changePwd").click(function () {
            var index = layer.open({
                type: 1,
                title: "修改密码",
                area: '400px',
                content: $('#passwordForm')
            });
            indexMap.set('#changePwd',index);
            // 表单赋值
            form.val("passwordForm", {
                "oldPassword": ""
                , "newPassword": ""
                , "confirmPassword": ""
            });
        });

        // 修改邮箱
        $("#changeEmail").click(function () {
            var index = layer.open({
                type: 1,
                title: "修改邮箱",
                area: '400px',
                content: $('#emailForm')
            });
            indexMap.set('#changeEmail',index);
            // 表单赋值
            form.val("emailForm", {
                "newEmail": ""
                , "code": ""
            });
        });

        // 登出
        $("#logout").click(function () {
            $.ajax({
                type: "GET",
                url: "login/out",
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        window.location.href = "login.html";
                    }
                }
            });
        });

        // 加载数据
        window.loadList = function (page) {
            page = page || 1;
            if(page == 1) $("#main").empty();
            $.ajax({
                type: "GET",
                url: "favorites/list",
                data: {"pageNum":page, "pageSize":4},
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        // 加载数据
                        var html = '';
                        $.each(result.data.list, function (i, c) {
                            var bookmarkClass = c.bookmark==1?"bookmark":"";
                            html += '<fieldset class="layui-elem-field layui-field-title ' + bookmarkClass + '" data-id="' + c.id + '">';
                            html += '   <legend onclick="editCategory(this)">' + c.name + '</legend>';
                            html += '   <ul class="favorites">';
                            if(c.favorites.length > 0) {
                                $.each(c.favorites, function (j, f) {
                                    html += '   <li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" onclick="openUrl(this)">';
                                    html += '       <div class="favorites-bg">';
                                    html += '           <img class="lazy" src="images/book.svg" lay-src="' + f.icon + '"/>';
                                    html += '       </div>';
                                    html += '       <p title="' + f.name + '">' + f.name + '</p>';
                                    html += '       <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                                    html += '   </li>';
                                    if(j == limit - 1){
                                        html += '<li class="layui-anim layui-anim-fadein" onclick="moreFavorites(' + c.id + ')">';
                                        html += '   <div class="favorites-bg">';
                                        html += '       <img src="images/more.svg"/>';
                                        html += '   </div>';
                                        html += '   <p title="显示更多">显示更多</p>';
                                        html += '</li>';
                                        return false;
                                    }
                                });
                            } else {
                                html += '<li class="layui-anim layui-anim-fadein" onclick="addFavorites(' + c.id + ')">';
                                html += '   <div class="favorites-bg">';
                                html += '       <img src="images/add.svg"/>';
                                html += '   </div>';
                                html += '   <p title="添加网址">添加网址</p>';
                                html += '</li>';
                            }
                            html += '   </ul>';
                            html += '</fieldset>';
                        });
                        $("#main").append(html);
                        imgRender();

                        if(page < result.data.pages) loadList(page + 1);
                    }
                },
                error: function(){
                    layer.msg("服务器异常", {icon: 2});
                }
            });
        };

        // 加载分类
        window.loadCategoryList = function () {
            $.ajax({
                type: "GET",
                url: "category/list",
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        var html = '';
                        $.each(result.data, function (i, c) {
                            html += '<option value="' + c.id + '" ' + (i == 0 ? 'selected' : '') +'>' + c.name + '</option>';
                        });
                        $("select[name='categoryId']").empty().append(html);
                        form.render('select','update-favorites');
                        form.render('select','add-favorites');
                    }
                }
            });
        };

        window.loadStarFavorites = function () {
            $.ajax({
                type: "GET",
                url: "favorites/star",
                dataType: "json",
                success: function (result) {
                    $("#starDiv").empty();
                    if(result.code == 0 && result.data.length > 0){
                        var html = '';
                        html += '<fieldset class="layui-elem-field layui-field-title">';
                        html += '   <legend style="font-size:16px;">常用网址</legend>';
                        html += '   <ul class="favorites">';
                        $.each(result.data, function (i, f) {
                            html += '   <li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" onclick="openUrl(this)">';
                            html += '       <div class="favorites-bg">';
                            html += '           <img class="lazy" src="images/book.svg" lay-src="' + f.icon + '"/>';
                            html += '       </div>';
                            html += '       <p title="' + f.name + '">' + f.name + '</p>';
                            html += '       <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                            html += '   </li>';
                        });
                        html += '   </ul>';
                        html += '</fieldset>';

                        $("#starDiv").append(html);
                        imgRender();
                    }
                }
            });
        };

        // 显示更多
        window.moreFavorites = function (categoryId) {
            layer.load();
            $.ajax({
                type: "GET",
                url: "favorites/more",
                data: {"categoryId": categoryId},
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        var html = '';
                        $.each(result.data, function (i, f) {
                            html += '<li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" onclick="openUrl(this)">';
                            html += '   <div class="favorites-bg">';
                            html += '       <img class="lazy" src="images/book.svg" lay-src="' + f.icon + '"/>';
                            html += '   </div>';
                            html += '   <p title="' + f.name + '">' + f.name + '</p>';
                            html += '   <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                            html += '</li>';
                        });
                        $("fieldset[data-id='" + categoryId + "']").find(".favorites").empty().append(html);
                        imgRender();
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                },
                error: function(){
                    layer.closeAll('loading');
                    layer.msg('服务器异常', {icon: 2});
                }
            });
        };

        // 删除收藏
        $("#deleteFavorites").click(function () {
            layer.confirm('确认删除收藏吗?', function(index){
                layer.close(index);
                layer.load();
                var data = form.val("update-favorites");
                $.ajax({
                    type: "GET",
                    url: "favorites/delete/" + data.id,
                    dataType: "json",
                    success: function (result) {
                        layer.closeAll('loading');
                        layer.close(indexMap.get('#update-favorites'));
                        if (result.code == 0) {
                            window.location.reload();
                        } else {
                            layer.msg("删除失败", {icon: 5});
                        }
                    }
                });
            });
        });

        // 清空收藏
        $("#clean").click(function () {
            layer.confirm('确认清空分类下所有收藏吗?', function(index){
                layer.close(index);
                layer.load();
                var data = form.val("update-category");
                $.ajax({
                    type: "POST",
                    url: "category/clean",
                    data: {"id": data.id},
                    dataType: "json",
                    success: function (result) {
                        layer.closeAll('loading');
                        layer.close(indexMap.get('#update-category'));
                        if (result.code == 0) {
                            window.location.reload();
                        } else {
                            layer.msg(result.msg, {icon: 2});
                        }
                    }
                });
            });
        });

        // 删除分类
        $("#deleteCategory").click(function () {
            layer.confirm('确认删除分类吗?', function(index){
                layer.close(index);
                layer.load();
                var data = form.val("update-category");
                $.ajax({
                    type: "GET",
                    url: "category/delete/" + data.id,
                    dataType: "json",
                    success: function (result) {
                        layer.closeAll('loading');
                        layer.close(indexMap.get('#update-category'));
                        if (result.code == 0) {
                            window.location.reload();
                        } else {
                            layer.msg(result.msg, {icon: 2});
                        }
                    }
                });
            });
        });

        // 编辑收藏
        window.editFavorites = function (obj, e) {
            window.event ? window.event.cancelBubble = true : e.stopPropagation();//阻止冒泡
            var index = layer.open({
                type: 1,
                title: "修改收藏",
                skin: 'to-fix-select',
                area: '400px',
                content: $('#update-favorites')
            });
            indexMap.set('#update-favorites',index);
            // 表单赋值
            $.ajax({
                type: "GET",
                url: "favorites/" + $(obj).parent().attr("data-id"),
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        let data = result.data;
                        //给表单赋值
                        form.val("update-favorites", {
                            "id": data.id
                            , "categoryId": data.categoryId
                            , "name": data.name
                            , "url": data.url
                            , "sort": data.sort
                            , "star": data.star
                            , "shortcut": data.shortcut
                        });
                    }
                }
            });
        };

        form.verify({
            confirmPassword: function (value, item) {
                if($("#newPassword").val() !== value){
                    return "两次输入密码不一致";
                }
            },
            sortNum: function (value, item) {
                if(value != ""){
                    if(isNaN(value)){
                        return "请输入0~9999之间的整数";
                    }else if(value%1 !== 0){
                        return "请输入0~9999之间的整数";
                    }else if(value > 9999){
                        return "请输入0~9999之间的整数";
                    }
                }
            },
            exitEmail: function (value, item) {
                var msg;
                $.ajax({
                    type: "GET",
                    url: 'register/email/' + value,
                    async: false, // 使用同步的方法
                    dataType: 'json',
                    success: function (result) {
                        if (result.code != 0) {
                            msg = "邮箱已存在";
                        }
                    }
                });
                return msg;
            },
            shortcut: function (value, item) {
                if(value !== ""){
                    if(!value.startsWith("打开") && !value.startsWith("Open")){
                        return '指令请以"打开"或"Open"开头';
                    }
                    var msg;
                    $.ajax({
                        type: "GET",
                        url: 'favorites/shortcut?key=' + value,
                        async: false, // 使用同步的方法
                        dataType: 'json',
                        success: function (result) {
                            if (result.code == 0 && result.data.id != $("#favoritesId").val()) {
                                msg = "指令已存在";
                            }
                        }
                    });
                    return msg;
                }
            },
            category: function (value, item) {
                var categoryId = form.val("update-category").id;
                var msg;
                $.ajax({
                    type: "GET",
                    url: 'category/check/' + value,
                    async: false, // 使用同步的方法
                    dataType: 'json',
                    success: function (result) {
                        if (result.code == 0 && result.data.id != categoryId) {
                            msg = "分类已存在";
                        }
                    }
                });
                return msg;
            }
        });

        form.on('switch(viewStyle)', function(data){
            if(data.elem.checked){
                $("#layuiBody").addClass("bookmark");
            }else{
                $("#layuiBody").removeClass("bookmark");
            }
            $.ajax({
                type: "POST",
                url: "user/style",
                data: {"viewStyle": data.elem.checked? 1 : 0}
            });
        });

        form.on('switch(starSwitch)', function(data){
            layer.load();
            $.ajax({
                type: "POST",
                url: "favorites/star",
                data: JSON.stringify({"id": $("#favoritesId").val(),"star": data.elem.checked? 1 : 0}),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        layer.msg("操作成功", {icon: 6});
                        loadStarFavorites();
                        // 退出搜索模式
                        $("#search_close").click();
                    } else {
                        layer.msg(result.msg, {icon: 5});
                        // 回退
                        $(data.elem).removeAttr("checked");
                        $(data.othis).removeClass("layui-form-onswitch");
                    }
                },
                error: function(){
                    layer.closeAll('loading');
                    layer.msg('服务器异常', {icon: 2});
                    // 回退
                    $(data.elem).removeAttr("checked");
                    $(data.othis).removeClass("layui-form-onswitch");
                }
            });
        });

        form.on('switch(bookmarkSwitch)', function(data){
            var categoryId = form.val("update-category").id;
            layer.load();
            $.ajax({
                type: "POST",
                url: "category/bookmark",
                data: JSON.stringify({"id": categoryId,"bookmark": data.elem.checked? 1 : 0}),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        layer.msg("操作成功", {icon: 6});
                        if(data.elem.checked){
                             $("fieldset[data-id=" + categoryId + "]").addClass("bookmark");
                        }else{
                             $("fieldset[data-id=" + categoryId + "]").removeClass("bookmark");
                        }
                    } else {
                        layer.msg(result.msg, {icon: 5});
                        // 回退
                        $(data.elem).removeAttr("checked");
                        $(data.othis).removeClass("layui-form-onswitch");
                    }
                },
                error: function(){
                    layer.closeAll('loading');
                    layer.msg('服务器异常', {icon: 2});
                    // 回退
                    $(data.elem).removeAttr("checked");
                    $(data.othis).removeClass("layui-form-onswitch");
                }
            });
        });

        // 新增收藏
        form.on('submit(addFavorites)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "favorites/save",
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#add-favorites'));
                    if (result.code == 0) {
                        window.location.reload();
                    } else {
                        layer.msg("添加失败", {icon: 5});
                    }
                }
            });
            return false;
        });

        // 保存密码
        form.on('submit(savePwd)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "password",
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        let data = result.data;
                        //给表单赋值
                        form.val("setting-pwd", {
                            "id": data.id
                            , "favoritesId": data.favoritesId
                            , "account": data.account
                            , "password": data.password
                        });
                        layer.msg("保存成功", {icon: 6});
                    } else {
                        layer.msg("保存失败", {icon: 5});
                    }
                }
            });
            return false;
        });

        // 修改邮箱
        form.on('submit(updateEmail)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "user/email",
                data: data.field,
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#editEmail'));
                    if (result.code == 0) {
                        layer.msg("修改成功", {icon: 6});
                    } else {
                        layer.msg("修改失败", {icon: 5});
                    }
                }
            });
            return false;
        });

        // 修改收藏
        form.on('submit(updateFavorites)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "favorites/save",
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#update-favorites'));
                    if (result.code == 0) {
                        window.location.reload();
                    } else {
                        layer.msg("修改失败", {icon: 5});
                    }
                }
            });
            return false;
        });

        // 修改分类
        form.on('submit(updateCategory)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "category",
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#update-category'));
                    if (result.code == 0) {
                        window.location.reload();
                    } else {
                        layer.msg("修改失败", {icon: 5});
                    }
                }
            });
            return false;
        });

        // 修改密码
        form.on('submit(updatePassword)', function (data) {
            layer.load();
            $.ajax({
                type: "POST",
                url: "user/password",
                data: data.field,
                dataType: "json",
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#changePwd'));
                    if (result.code == 0) {
                        layer.msg('修改成功', {icon: 6});
                        // 退出
                        setTimeout(function () {
                            $("#logout").trigger("click");
                        }, 1000);
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
            });
            return false;
        });

        window.position = function(id){
            var offsetTop = $("fieldset[data-id="+id+"]").get(0).offsetTop;
            $("#layuiBody").animate({scrollTop: offsetTop}, 200);
        };

        window.imgRender = function(){
            // 触发scroll模拟render
            $("#layuiBody").scroll();
        };

        window.loadUserInfo = function(){
            $.ajax({
                type: "GET",
                url: "user/info",
                dataType: "json",
                success: function (result) {
                    $(".lGDtb").fadeOut();
                    if (result.code == 0) {
                        var user = result.data;
                        $("#username").text(user.username.substring(0, 4));
                        form.val("styleSelect", {"viewStyle": user.viewStyle});
                        if(user.viewStyle == 1)$("#layuiBody").addClass("bookmark");
                    }
                }
            });
        };

        window.initClipboard = function(){
            var clipboard = new ClipboardJS('#accountCopy');
            clipboard.on('success', function(e) {layer.msg("复制成功");});
            clipboard.on('error', function(e) {layer.msg("复制失败");});
            var clipboard1 = new ClipboardJS('#passwordCopy');
            clipboard1.on('success', function(e) {layer.msg("复制成功");});
            clipboard1.on('error', function(e) {layer.msg("复制失败");});
        };

        window.initCatalog = function(){
            $.ajax({
                type: "GET",
                url: "category/catalog",
                dataType: "json",
                success: function (result) {
                    if (result.code == 0) {
                        var html = '';
                        $.each(result.data, function (i, c) {
                            html += '<li><a href="javascript:;" onclick="position(' + c.id + ')"><cite>' + c.name + '</cite></a></li>';
                        });
                        $("#catalogList").empty().append(html);
                        // 绑定点击事件
                        $("#catalogList a").on('click',function(){
                            $("#catalogList a.layui-this").removeClass("layui-this");
                            $(this).addClass("layui-this");
                        });
                    }
                }
            });
        };

        $("#slideBtn").click(function(){
            layer.open({
              title: '目录'
              ,content: $("#catalogList")
              ,type: 1
              ,skin: 'catalog'
              ,offset: 'catalog'
              ,maxHeight: 600
            });
        });

        // 页面加载完成执行
        $(function () {
            // 执行加载动画
            $(".lGDtb").fadeIn();
            // 加载用户信息
            loadUserInfo();
            // 加载常用网址
            loadStarFavorites();
            // 加载数据
            loadList();
            // 加载分类
            loadCategoryList();
            // 初始化剪贴板插件
            initClipboard();
            // 初始化目录
            initCatalog();
        });
    });
</script>
</body>
</html>